#include "key_handler.h"
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "FreeRTOS.h"
#include "task.h"
#include "LOG.h"

// 按键配置
#define BUTTON_DEBOUNCE_TIME_MS 20
#define BUTTON_DEFAULT_LONG_PRESS_TIME_MS 1000

// 按键引脚映射
static const uint8_t key_pins[] = {
    [KEY_TYPE_WAIT] = KEY1_PIN,     // 倒计时按键
    [KEY_TYPE_ALARM1] = KEY4_PIN,   // 闹钟1按键
    [KEY_TYPE_ALARM2] = KEY2_PIN,   // 闹钟2按键
    [KEY_TYPE_HOME] = KEY3_PIN      // HOME按键
};

// 按键状态结构体
typedef struct {
    bool last_button_state;         // 上一次按键状态
    bool current_button_state;      // 当前按键状态
    uint32_t press_start_time;      // 按下开始时间
    bool is_pressed;                // 是否已按下
} key_handler_state_t;  // 修改结构体名称以避免冲突

// 按键状态数组
static key_handler_state_t key_states[4]; // 使用新的结构体名称

// 长按时间配置
static uint32_t long_press_time_ms = BUTTON_DEFAULT_LONG_PRESS_TIME_MS;

// 按键事件回调函数指针
static key_event_callback_t event_callback = NULL;

// 初始化按键处理模块
void key_handler_init(void)
{
    // 初始化所有按键GPIO为输入模式
    for (int i = 0; i < 4; i++) {
        gpio_init(key_pins[i]);
        gpio_set_dir(key_pins[i], GPIO_IN);
        gpio_pull_up(key_pins[i]); // 启用上拉电阻
        
        // 初始化按键状态
        key_states[i].last_button_state = true;   // 默认未按下（上拉）
        key_states[i].current_button_state = true;
        key_states[i].press_start_time = 0;
        key_states[i].is_pressed = false;
    }
    
    LOG_INFO("Key handler initialized: WAIT=%d, ALARM1=%d, ALARM2=%d, HOME=%d", 
             KEY1_PIN, KEY4_PIN, KEY2_PIN, KEY3_PIN);
}

// 设置长按时间
void key_handler_set_long_press_time(uint32_t time_ms)
{
    long_press_time_ms = time_ms;
    LOG_INFO("Key long press time set to %d ms", time_ms);
}

// 注册按键事件回调函数
void key_handler_register_callback(key_event_callback_t callback)
{
    event_callback = callback;
}

// 处理单个按键
static void process_key(key_type_t key_type)
{
    uint8_t key_pin = key_pins[key_type];
    key_handler_state_t *state = &key_states[key_type];  // 使用新的结构体名称
    
    // 读取当前按键状态（低电平为按下）
    bool raw_button_state = !gpio_get(key_pin); // 取反，因为上拉时未按下为高电平

    // 简单的去抖动处理
    if (raw_button_state != state->last_button_state) {
        vTaskDelay(pdMS_TO_TICKS(BUTTON_DEBOUNCE_TIME_MS));
        state->current_button_state = !gpio_get(key_pin);

        if (state->current_button_state != state->last_button_state) {
            if (state->current_button_state) {
                // 按键按下
                state->press_start_time = xTaskGetTickCount();
                state->is_pressed = true;
                LOG_DEBUG("Key %d pressed", key_pin);
                
                // 调用回调函数通知按键按下事件
                if (event_callback != NULL) {
                    event_callback(key_type, KEY_EVENT_PRESSED);
                }
            } else {
                // 按键释放
                if (state->is_pressed) {
                    uint32_t press_duration = xTaskGetTickCount() - state->press_start_time;
                    LOG_DEBUG("Key %d released, duration: %d ms", key_pin, press_duration * portTICK_PERIOD_MS);

                    if (press_duration >= pdMS_TO_TICKS(long_press_time_ms)) {
                        // 长按事件
                        LOG_DEBUG("Key %d long pressed", key_pin);
                        if (event_callback != NULL) {
                            event_callback(key_type, KEY_EVENT_LONG_PRESSED);
                        }
                    } else {
                        // 短按事件
                        LOG_DEBUG("Key %d short pressed", key_pin);
                        // 短按事件已经在按下时处理，这里只处理释放
                        if (event_callback != NULL) {
                            event_callback(key_type, KEY_EVENT_RELEASED);
                        }
                    }
                    state->is_pressed = false;
                }
            }
        }
    }

    state->last_button_state = state->current_button_state;
}

// 处理所有按键
void key_handler_process(void)
{
    // 处理各个按键
    process_key(KEY_TYPE_WAIT);
    process_key(KEY_TYPE_ALARM1);
    process_key(KEY_TYPE_ALARM2);
    process_key(KEY_TYPE_HOME);
}
